package com.test.oauth2;

import com.test.mapper.SysOauthMapper;
import com.test.pojo.SysOauthClient;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
@Log4j2
public class CustomClientDetailsService implements ClientDetailsService {

    @Autowired
    private SysOauthMapper sysOauthMapper;


    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        log.info("客户端查询:" + clientId);
        SysOauthClient client = sysOauthMapper.selectOneByClientId(clientId);
        log.info("查询到的信息:{}",client.toString());
        if (client == null) {
            log.error("未找到客户端ID: " + clientId);
            throw new ClientRegistrationException("客户端ID无效");
        }

        BaseClientDetails clientDetails = new BaseClientDetails(
                client.getClientId(),
                null,
                client.getScope(),
                client.getAuthorizedGrantTypes(),
                client.getAuthorities(),
                client.getWebServerRedirectUri()
        );

        clientDetails.setClientSecret(client.getClientSecret());
        clientDetails.setAccessTokenValiditySeconds(client.getAccessTokenValidity());
        clientDetails.setRefreshTokenValiditySeconds(client.getRefreshTokenValidity());

        if ("是".equals(client.getAutoapprove())) {
            clientDetails.setAutoApproveScopes(Arrays.asList("true"));
        }
        log.info("最终返回数据:" + clientDetails);
        return clientDetails;
    }
}
